<?php
namespace app\index\controller;

use app\common\model\User as UserModel;
use app\common\model\Order as OrderModel;
use think\Controller;
use think\Loader;
require_once '../vendor/alipay/pagepay/service/AlipayTradeService.php';
require_once '../vendor/alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
class Order extends Controller
{
	public function index()
	{
		return $this->fetch();
	}

	public function pay()
	{

		$config = config('alipay');

		//商户订单号，商户网站订单系统中唯一订单号，必填
	    $data['out_trade_no'] = date("YmdHis").session('user')->user_id.mt_rand(100,999);
	    //订单名称，必填
	    $data['subject'] = "layuiAdmin 通用后台管理模板";
	    //付款金额，必填
	    $data['total_amount'] = 0.1;
	    //商品描述，可空
	    $data['body'] = "layuiAdmin 通用后台管理模板-一年";

	    $data['user_id'] = session('user')->user_id;

	    OrderModel::create($data);

	    //构造参数
		$payRequestBuilder = new \AlipayTradePagePayContentBuilder();

		$payRequestBuilder->setBody($data['body']);
		$payRequestBuilder->setSubject($data['subject']);
		$payRequestBuilder->setTotalAmount($data['total_amount']);
		$payRequestBuilder->setOutTradeNo($data['out_trade_no']);

		$aop = new \AlipayTradeService($config);

		$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

		//输出表单
		var_dump($response);
		exit;
	}

	public function notify_url()
	{

		$config = config('alipay');

		$data=$_POST;

		$alipaySevice = new \AlipayTradeService($config); 

		$result = $alipaySevice->check($data);

		if($result){

			$order = OrderModel::where('out_trade_no',$data['out_trade_no'])->find();

			if($order->total_amount==$data['total_amount']){
				$order->status = 1;
				$order->save();
				echo "success";
				exit;
			}
		}

	}

	public function return_url()
	{
		$config = config('alipay');

		$data = $_GET;

		$alipaySevice = new \AlipayTradeService($config); 

		$result = $alipaySevice->check($data);

		if($result){

			$order = OrderModel::where('out_trade_no',$data['out_trade_no'])->find();

			if($order->total_amount==$data['total_amount']){
				$order->status = 1;
				$order->save();
				$this->success("支付成功",url('index/index/index'));
			}

		}
	}
}